import {
  getNewCartGoods,
  reqMergeLocalCart,
  reqFindCartList,
  reqInsertCart,
  reqDeleteCart,
  reqUpdateCartSku,
  reqCheckAllCart
} from '@/api/cart'
// 购物车状态
export default {
  namespaced: true,
  state: () => {
    return {
      list: []
    }
  },
  // 修改数据
  mutations: {
    // 设置整个列表
    setList (state, list) {
      state.list = list
    },
    // 无效商品列表
    ineffectiveList (state) {
      return state.list.filter(item => !(item.stock > 0 && item.isEffective))
    },
    // 添加购物车数据
    insertCart (state, goods) {
      const index = state.list.findIndex(item => item.skuId === goods.skuId)
      if (index === -1) {
        // 没找到
        state.list = [goods, ...state.list]
      } else {
        state.list[index].count += goods.count
      }
      console.log(20, state.list)
    },
    // 删除购物车数据
    deleteCart (state, skuId) {
      const index = state.list.findIndex(item => item.skuId === skuId)
      state.list.splice(index, 1)
    },
    // 更新购物车商品信息
    updateCart (state, goods) {
      const list = state.list.find(item => item.skuId === goods.skuId)
      list.isEffective = goods.isEffective
      list.nowPrice = goods.nowPrice
      list.stock = goods.stock
    },
    // 更新购物车商品信息单个
    updateCartSingle (state, goods) {
      const index = state.list.findIndex(item => item.skuId === goods.skuId)
      state.list[index] = goods
    },
    // 单选框控制
    CheckboxSingle (state, { goods, selected }) {
      const index = state.list.findIndex(item => item.skuId === goods.skuId)
      state.list[index].selected = selected
    },
    // 全选控制单选
    checkEffectAll (state, selected) {
      state.list.forEach(item => {
        // console.log(48, item.isEffective)
        item.selected = selected
      })
    }
  },
  // 异步
  actions: {
    // 添加购物车数据
    asyncInertCart (store, goods) {
      // 包装 Promise 执行resolve。then里执行后续程序
      return new Promise((resolve, reject) => {
        if (store.rootState.user.profile.token) {
          // 已登录
          // console.log('已登录')
          const { skuId, count } = goods
          reqInsertCart({ skuId, count }).then((res) => {
            // console.log(72, res)
            store.dispatch('asyncUpdateCart').then((res) => {
              resolve()
            })
          })
        } else {
          // 未登录
          // console.log('未登录')
          store.commit('insertCart', goods)
          resolve()
        }
      })
    },
    // 删除购物车商品 根据唯一的skuId查找删除
    asyncDeleteCart (store, skuId) {
      return new Promise((resolve, reject) => {
        // 判断登录情况
        if (store.rootState.user.profile.token) {
        // 已登录
          // console.log('已登录')
          reqDeleteCart(skuId).then((res) => {
            store.dispatch('asyncUpdateCart').then((res) => {
              resolve()
            })
          })
        } else {
          store.commit('deleteCart', skuId)
          resolve()
        }
      })
    },
    // 更新购物车商品信息
    asyncUpdateCart (store) {
      return new Promise((resolve, reject) => {
        // 判断登录情况
        if (store.rootState.user.profile.token) {
          // console.log('登录了')
          reqFindCartList().then(({ result }) => {
            store.commit('setList', result)
          })
          resolve()
        } else {
          const requestArr = store.state.list.map(item => getNewCartGoods(item.skuId))
          ;(async () => {
            const res = await Promise.all(requestArr)
            console.log(res, 76)
            res.forEach((item, index) => {
              store.commit('updateCart', {
                skuId: store.state.list[index].skuId,
                ...item.result
              })
            })
          })()
          resolve()
        }
      })
    },
    // 更新购物车商品信息单个
    asyncUpdateCartSingle (store, goods) {
      return new Promise((resolve, reject) => {
        if (store.rootState.user.profile.token) {
          reqUpdateCartSku(goods).then((res) => {
            console.log(134, res)
            resolve()
          })
        } else {
          store.commit('updateCartSingle', goods)
          resolve()
        }
      })
    },
    // 单选框控制
    asyncCheckboxSingle (store, { goods, selected }) {
      if (store.rootState.user.profile.token) {
        reqUpdateCartSku({
          skuId: goods.skuId,
          selected: selected
        }).then((res) => {
          store.dispatch('asyncUpdateCart')
        })
      } else {
        store.commit('CheckboxSingle', { goods, selected })
      }
    },
    // 全选控制单选
    asyncCheckEffectAll (store, selected) {
      if (store.rootState.user.profile.token) {
        const skuIdS = store.getters.effectiveList.map(item => item.skuId)
        reqCheckAllCart({
          selected,
          ids: skuIdS
        }).then((res) => {
          // console.log(172, res)
          store.dispatch('asyncUpdateCart')
        })
      } else {
        store.commit('checkEffectAll', selected)
      }
    },
    async asyncMergeLocalCart (store) {
      // 存储token后调用本地接口同步
      const cartList = store.state.list.map(({ skuId, selected, count }) => {
        return { skuId, selected, count }
      })
      await reqMergeLocalCart(cartList)
      // 合并成功后，从后端获取最新购物车列表替换本地
    }
  },
  // 计算
  getters: {
    // 计算有效商品列表 isEffective = true  filter
    effectiveList (state) {
      return state.list.filter(item => item.stock > 0 && item.isEffective)
    },
    // 有效商品总数量 把effctiveList中的每一项的count叠加起来
    effectiveTotal (state, getters) {
      return getters.effectiveList.reduce((sum, item) => sum + item.count, 0)
    },
    // 总钱数  = 所有单项的钱数累加  单项的钱数 = 数量 * 单价
    effectiveTotalPrice (state, getters) {
      return getters.effectiveList.reduce((sun, item) => sun + (item.count * item.nowPrice), 0).toFixed(2)
    },
    // 已选择的有效商品列表
    selectedList (state, getters) {
      return getters.effectiveList.filter(item => item.selected)
    },
    // 已选择的有效商品列表总件数
    selectedListTotal (state, getters) {
      return getters.selectedList.reduce((total, item) => total + item.count, 0)
    },
    // 已选择的有效商品列表总价格
    selectedListTotalPrice (state, getters) {
      return getters.selectedList.reduce((total, item) => total + item.count * item.nowPrice, 0).toFixed(2)
    },
    // 小选控制全选
    isAllEffectSelected (state, getters) {
      // console.log(123, getters.effectiveList)
      return getters.effectiveList.every(item => item.selected === true)
    }
  }
}
